from machine import UART
import select
from task import PollTask

SERIAL_1 = 1
SERIAL_2 = 2


class UART_Stream:
    def __init__(self, port=SERIAL_2, baud_rate=115200):
        self.__uart = UART(port, baud_rate)

    def reopen(self, baud_rate):
        self.__uart.init(baud_rate)

    def close(self):
        self.__uart.deinit()

    def receiver_buffer_size(self):
        return self.__uart.any()

    def register_2_poller(self, poller):
        poller.register(self.__uart, select.POLLIN)

    def read_exists(self):
        return self.__uart.read()

    def write(self, data):
        self.__uart.write(data)


uart_2 = UART_Stream(SERIAL_2)


class UART_ReceiveTask(PollTask):
    def __init__(self, uart, callback):
        super().__init__()
        self.__uart = uart
        self.__callback = callback

    def read(self):
        return self.__uart.read_exists()

    def load_resource(self, poll):
        self.__uart.register_2_poller(poll)

    def on_poll_result(self, results):
        if results and len(results) > 0:
            data = self.read()
            if data and len(data) > 0:
                self.__callback(data)

